﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

/*
 * 脚本功能：Http请求类
 * 编写日期：2018.12.13
 * 编写人：HYZ
 */
namespace CFrame.Tools
{
    public class HttpHelper : MonoBehaviour
    {
        public static HttpHelper Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = GameObject.FindObjectOfType<HttpHelper>();
                }
                if (_instance == null)
                {
                    GameObject go = new GameObject("HttpHelper");
                    _instance = go.AddComponent<HttpHelper>();
                }
                return _instance;
            }
        }
        private static HttpHelper _instance;

        /// <summary>
        /// Get类型请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="CallBack"></param>
        public void Get(string url, System.Action<string> CallBack)
        {
            StartCoroutine(GetData(url, CallBack));
        }

        IEnumerator GetData(string url, System.Action<string> CallBack)
        {
            WWW www = new WWW(url);
            yield return www;
            if (www.error != null)
            {
                Debuger.LogError("网络请求错误:" + www.error);
            }
            else
            {
                CallBack(string.IsNullOrEmpty(www.text) ? "" : www.text);
            }
        }

        /// <summary>
        /// Post类型请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="header"></param>
        /// <param name="CallBack"></param>
        public void Post(string url, Dictionary<string, string> header, System.Action<string> CallBack)
        {
            StartCoroutine(PostData(url, header, CallBack));
        }

        IEnumerator PostData(string url, Dictionary<string, string> header, System.Action<string> CallBack)
        {
            WWW www = new WWW(url, null, header);
            yield return www;
            if (www.error != null)
            {
                Debuger.LogError("网络请求错误:" + www.error);
            }
            else
            {
                CallBack(string.IsNullOrEmpty(www.text) ? "" : www.text);
            }
        }
    }
}
